﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using DotNet.Model;
using NBear.Mapping;
using DotNet.Utilities;
//using HF.WorkFlow.Template;
using KingRoad.EPM.Web.ViewModels;
//using HF.Framework.DataContract;
//using HF.Framework.DataClientDBAgent;
//using HF.WorkFlow.Engine;
//using KingRoad.EPM.InvestmeBLL;
//using KingRoad.EPM.InvestmeIBLL;
//using KingRoad.EPM.InvestmeEntity;
using KingRoad.EPM.Web.Util;
using KingRoad.EPM.Common.Configuration;
using System.Text;
using System.Xml;
using DotNet.Service;
using KingRoad.EPM.ProjectInfoIBLL;
using KingRoad.EPM.ProjectInfoEntity;
using DotNet.Model.MyEntity;
using KingRoad.EPM.ProjectInfoBLL;
using KingRoad.EPM.Common.Enum;
using KingRoad.EPM.DeviceBLL.UIRules;
using KingRoad.EPM.DeviceDAL;
using KingRoad.EPM.DeviceEntity.Model;
using KingRoad.EPM.DeviceDAL.BllRoadwayService;

namespace KingRoad.EPM.Web.Controllers
{
    public class HomeController : Controller
    {
        OperateXml operateXml = new OperateXml();

        public BllRoadwayUIRule BllRoadwayUIRule = new BllRoadwayUIRule(new BllRoadwayService());

        private IProject_SegmentBLL _segmentBLL = null;
        //private IWF_ChangeApplyBLL _changeApplyBLL = null;
        //private IWF_ChangeInformBLL _changeInformBLL = null;
        //private IWF_ChangeOrderBLL _changeOrderBLL = null;
        private OrganizeService _organizeService = null;
        //private IProject_BrowserHistoryBLL _BrowserHistoryBLL = null;
        //private IProject_InstructionsBLL _Instructions = null;
        private IProject_PrjInfoBLL _prjInfoBLL = null;
        // GET: /WorkFlow/ClaimingTask/
        public HomeController()
        {
            _segmentBLL = new KingRoad.EPM.ProjectInfoBLL.Project_SegmentBLL();
            //_changeApplyBLL = new WF_ChangeApplyBLL();
            //_changeInformBLL = new WF_ChangeInformBLL();
            //_changeOrderBLL = new WF_ChangeOrderBLL();
            _organizeService = new OrganizeService();
            //_BrowserHistoryBLL = new Project_BrowserHistoryBLL();
            //_Instructions = new KingRoad.EPM.ProjectInfoBLL.Project_InstructionsBLL();
            _prjInfoBLL = new Project_PrjInfoBLL();
        }
        //
        // GET: /Home/
        //[UserAuthorize]
        public ActionResult Index()
        {
            #region //取消 WS 2011.12.22
            ////获得当前用户待办工作列表
            //DataTable dt = WorkFlowInstance.WorkflowClaimedTask(_organizeService.GetStaffIdByUserName(), 5);
            ////获得当前用户新到工作列表
            //DataTable mainDt = WorkFlowInstance.ClaimWorkTask(_organizeService.GetStaffIdByUserName(), 5);
            //List<PROJECT_SEGMENT> segList = _segmentBLL.GetNowadayOrglist();
            //List<TaskDetail> list = new List<TaskDetail>();
            //ObjectMapper mapper = new ObjectMapper(typeof(DataRow), typeof(TaskDetail));
            //TaskDetail detail = null;
            //if (dt != null)
            //{
            //    foreach (DataRow dr in dt.Rows)
            //    {
            //        detail = mapper.ConvertObject(dr) as TaskDetail;
            //        detail.State = 2;
            //        list.Add(detail);
            //    }
            //}
            //if (mainDt != null)
            //{
            //    //获取过滤后的新到工作数据           
            //    foreach (DataRow dr in mainDt.Rows)
            //    {
            //        string caption = dr["FlowInsCaption"].ToString();
            //        string[] captionStrs = caption.Split('_');
            //        detail = mapper.ConvertObject(dr) as TaskDetail;
            //        detail.State = 1;
            //        if (captionStrs[0] == "计日工申报审查")
            //        {
            //            //若当前登录人所属单位关联标段有此标段，则纳入新到工作列表
            //            foreach (PROJECT_SEGMENT segDetail in segList)
            //            {
            //                if (segDetail.SEGMENT_CODE == captionStrs[1])
            //                    list.Add(detail);
            //            }
            //        }
            //        else if (captionStrs[0] == "施工计量")
            //        {
            //            foreach (PROJECT_SEGMENT segDetail in segList)
            //            {
            //                if (segDetail.SEGMENT_CODE == captionStrs[1])
            //                    list.Add(detail);
            //            }
            //        }
            //        else
            //        {
            //            list.Add(detail);
            //        }
            //    }
            //}
            #endregion
            ViewBag.UserName = UserService.CurrUserInfo.RealName;
            ViewBag.OrgName = UserService.CurrUserInfo.CompanyFullName;
            ViewBag.RoleName = UserService.CurrUserInfo.RoleName;
            ViewBag.DutyName = UserService.CurrUserInfo.WorkgroupFullName;//获取岗位名称
            ViewBag.DutyID = UserService.CurrUserInfo.WorkgroupId;//当前岗位ID

            #region 用户快捷操作模块菜单list ThinkWang 2012-9-25 17:22:54
            IList<BaseModuleEntity> list = new UserService().GetModulelist() ?? new List<BaseModuleEntity>();
            ViewBag.FastBarList = list;
            #endregion
            #region 当前选择项目信息 ThinkWang 2013-5-27 14:36:16
            //Themes充当 当前项目id
            int curProId = 0;
            //string curProName = "请选择项目";
            //if (!string.IsNullOrWhiteSpace(UserService.CurrUserInfo.Themes) && UserService.CurrUserInfo.Themes != "0")
            //{//如果 当前项目id已经有了
            //    curProId = (string.IsNullOrWhiteSpace(UserService.CurrUserInfo.Themes) ? 0 : int.Parse(UserService.CurrUserInfo.Themes));
            //    var curProModel = _prjInfoBLL.GetEntityById(curProId);
            //    if (curProModel != null)
            //        curProName = curProModel.PRJINFO_NAME;
            //}
            //else
            //{ //如果当前项目id没有值，获取用户能查看的项目列表，如果用户只能看1个项目，就将这个id设为当前项目id
            //    var listPro = _prjInfoBLL.GetPrjinfoByUserID();
            //    if (listPro != null && listPro.Count == 1)
            //    {
            //        curProId = listPro[0].PRJINFO_ID;
            //        curProName = listPro[0].PRJINFO_NAME;
            //        SetProjectCookie(curProId);
            //        UserService.CurrUserInfo.Themes = curProId > 0 ? curProId.ToString() : "";
            //        Settings.Refresh();
            //    }
            //}

            ViewBag.CurProId = curProId;//当前项目id
            //if (curProId > 0)
            //SetWorkFlowId(curProId);

            //    ViewBag.CurProName = curProName;//项目名称
            // ViewBag.IsSA = UserService.CurrUserInfo.IsAdministrator;//是否是超级管理员，超级管理员登录 不用选择项目
            ViewBag.IsSA = true;
            #endregion

            string newXml = operateXml.ReadXml();
            string[] tempList = newXml.Split(';');
            ViewBag.Copyright = tempList[0];
            ViewBag.Href = tempList[1];
            ViewBag.CompanyName = tempList[2];
            ViewBag.Phone = tempList[3];
            ViewBag.VersionNumber = tempList[5];
            ViewBag.SysTitle = tempList[6];
            //zbl 中心点
            ViewBag.discenter = UserService.CurrUserInfo.DepartmentId.ToString();

            return View();
        }

        /// <summary>
        /// 左侧菜单树
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult LeftMenu()
        {
            //获取权限系统中当前登录人所能访问的所有菜单
            List<BaseModuleEntity> list = new ModuleService().GetCurrentModules() as List<BaseModuleEntity>;
            //如果当前登录人是管理员，则进行模块过滤，只显示权限管理、日志管理 WS 2011.11.8
            List<BaseModuleEntity> adminList = new List<BaseModuleEntity>();
            if (UserService.CurrUserInfo.IsAdministrator)
            {
                string tags = "PAY|PERMISSION|LOG";
                int permissionID = 0, logID = 0;
                //1找到含有这三个标记的模块
                list.ForEach(x =>
                    {
                        if (!String.IsNullOrEmpty(x.Code))
                        {
                            if (tags.Contains(x.Code))
                                adminList.Add(x);
                            if (x.Code == "PERMISSION")
                                permissionID = x.Id.Value;
                            if (x.Code == "LOG")
                                logID = x.Id.Value;
                        }
                    });
                //2找到所有父节点是后两个tag的所有模块
                list.ForEach(x =>
                    {
                        if (x.ParentId.HasValue)
                            if (x.ParentId.Value == permissionID || x.ParentId.Value == logID)
                                adminList.Add(x);
                    });
                list = adminList;
            }
            //else
            //{
            //只有业务人员构造工作模块
            //WFStartMenu();//构造工作流起草菜单
            //WFCtrlMenu();//可办理工作菜单
            //}
            if (list != null)
            {
                list.ForEach(x =>
                {
                    if (x.Code == BaseSystemInfo.RootMenuCode)
                    {
                        ViewBag.PID = x.Id.Value.ToString();
                    }
                });
            }

            return View(list);
        }

        /// <summary>
        /// 获取jqGrid新到工作
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ActionResult GetClaimingTasks(QueryBase query, int topsize = 5, string workType = "")
        {
            List<PROJECT_SEGMENT> segList = null;
            DataTable mainDt = null;
            //if (UserService.CurrUserInfo.WorkgroupId.HasValue)
            //    mainDt = WorkFlowInstance.ClaimWorkTaskDuty(UserService.CurrUserInfo.Id, UserService.CurrUserInfo.WorkgroupId.Value.ToString(), topsize);
            //else
            //    mainDt = WorkFlowInstance.ClaimWorkTask(UserService.CurrUserInfo.Id, topsize);
            //List<TaskDetail> list = new List<TaskDetail>();
            //ObjectMapper mapper = new ObjectMapper(typeof(DataRow), typeof(TaskDetail));
            //if (mainDt != null)
            //{
            //    foreach (DataRow dr in mainDt.Select("flowinscaption like'" + workType + "%'", "OperDateTime DESC"))
            //    {
            //        string caption = dr["FlowInsCaption"].ToString();
            //        string[] captionStrs = caption.Split('_');
            //        //根据不用的申报流程和当前登录人来获取对应负责的标段
            //        bool flag = false;
            //        if (dr["workflowId"].ToString() == WorkFlowSetting.Instance.VisionMeasureWFId || dr["workflowId"].ToString() == Settings.Instance.VisionFundPlanWFId
            //            || dr["workflowId"].ToString() == Settings.Instance.VisionImprestWFId)
            //        {
            //            segList = _segmentBLL.GetNowadayOrglist(1); flag = true;
            //        }
            //        else if (dr["workflowId"].ToString() == WorkFlowSetting.Instance.VerifyMeasureWFId || dr["workflowId"].ToString() == Settings.Instance.VerifyFundPlanWFId
            //            || dr["workflowId"].ToString() == Settings.Instance.VerifyImprestWFId)
            //        {
            //            segList = _segmentBLL.GetNowadayOrglist(3); flag = true;
            //        }
            //        else if (dr["workflowId"].ToString() == WorkFlowSetting.Instance.SupervisingWFId || dr["workflowId"].ToString() == Settings.Instance.SupervisingPlanWFId
            //            || dr["workflowId"].ToString() == Settings.Instance.SupervisingImprestWFId)
            //        {
            //            segList = _segmentBLL.GetNowadayOrglist(4); flag = true;
            //        }
            //        else
            //        {
            //            segList = _segmentBLL.GetNowadayOrglist(); flag = true;
            //        }
            //        if (flag)
            //        {
            //            foreach (PROJECT_SEGMENT model in segList)
            //            {
            //                if (model.SEGMENT_CODE.Trim().Contains(captionStrs[1].Trim()))
            //                    if (!(list.FindAll(m => m.WorkFlowNo == (mapper.ConvertObject(dr) as TaskDetail).WorkFlowNo).Count > 0))
            //                        list.Add(mapper.ConvertObject(dr) as TaskDetail);
            //            }
            //        }
            //        else
            //        {
            //            list.Add(mapper.ConvertObject(dr) as TaskDetail);
            //        }
            //        #region 废弃的代码段
            //        //if (captionStrs[0] == "计日工申报审查")
            //        //{
            //        //    //若当前登录人所属单位关联标段有此标段，则纳入新到工作列表
            //        //    foreach (PROJECT_SEGMENT segDetail in segList)
            //        //    {
            //        //        if (segDetail.SEGMENT_CODE == captionStrs[1])
            //        //            list.Add(mapper.ConvertObject(dr) as TaskDetail);
            //        //    }
            //        //}
            //        //else if (captionStrs[0] == "索赔申报")
            //        //{

            //        //}
            //        //else if (captionStrs[0] == "材差申报")
            //        //{

            //        //}
            //        //else if (captionStrs[0] == "施工计量")
            //        //{
            //        //    foreach (PROJECT_SEGMENT segDetail in segList)
            //        //    {
            //        //        if (segDetail.SEGMENT_CODE == captionStrs[1])
            //        //            list.Add(mapper.ConvertObject(dr) as TaskDetail);
            //        //    }
            //        //}
            //        //else if (captionStrs[0] == "监理计量")
            //        //{
            //        //    List<PROJECT_SEGMENT> visionList = _segmentBLL.GetNowadayOrglist(1);
            //        //    foreach (PROJECT_SEGMENT visionDetail in visionList)
            //        //    {
            //        //        if (visionDetail.SEGMENT_CODE == captionStrs[1])
            //        //            list.Add(mapper.ConvertObject(dr) as TaskDetail);
            //        //    }
            //        //}
            //        //else if (captionStrs[0] == "设计计量")
            //        //{
            //        //    List<PROJECT_SEGMENT> designList = _segmentBLL.GetNowadayOrglist(2);
            //        //    foreach (PROJECT_SEGMENT designDetail in designList)
            //        //    {
            //        //        if (designDetail.SEGMENT_CODE == captionStrs[1])
            //        //            list.Add(mapper.ConvertObject(dr) as TaskDetail);
            //        //    }
            //        //}
            //        //else
            //        //{
            //        //    list.Add(mapper.ConvertObject(dr) as TaskDetail);
            //        //}
            //        #endregion
            //    }
            //}
            //var jqGridData = WebUtility.TojqGridData<TaskDetail>(list, query);
            return null;
        }


        /// <summary>
        /// 获取jqGrid待办工作列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ActionResult GetClaimedTasks(QueryBase query, int topsize = 5, string workType = "")
        {
            DataTable dt = null;
            //if (UserService.CurrUserInfo.WorkgroupId.HasValue)
            //    dt = WorkFlowInstance.WorkflowClaimedTaskDuty(_organizeService.GetStaffIdByUserName(), UserService.CurrUserInfo.WorkgroupId.Value.ToString(), 5);
            //else
            //dt = WorkFlowInstance.WorkflowClaimedTask(UserService.CurrUserInfo.Id, topsize);
            //List<TaskDetail> list = new List<TaskDetail>();
            //ObjectMapper mapper = new ObjectMapper(typeof(DataRow), typeof(TaskDetail));
            //if (dt != null)
            //{
            //    foreach (DataRow dr in dt.Select("flowinscaption like'" + workType + "%'", "OperDateTime DESC"))
            //    {
            //        if (dr["OperType"].ToString() == "6" && dr["OperContent"].ToString() != UserService.CurrUserInfo.WorkgroupId.Value.ToString()) continue;
            //        处理由于退回，操作人在前台显示的问题
            //        if (dr["pOperatedDes"].ToString().Contains("["))
            //            dr["OperatedDes"] = dr["pOperatedDes"].ToString().Replace("被[", "").Replace("]退回", "");
            //        else
            //            dr["OperatedDes"] = dr["pOperatedDes"] != DBNull.Value ? dr["pOperatedDes"] : dr["OperContentText"];
            //        list.Add(mapper.ConvertObject(dr) as TaskDetail);
            //    }
            //}
            //var jqGridData = WebUtility.TojqGridData<TaskDetail>(list, query);
            return null;// Json(jqGridData);
        }


        /// <summary>
        /// 当前登录人可起草工作 WS 2011-10-20
        /// </summary>
        /// <returns></returns>
        private void WFStartMenu()
        {
            //List<WFMenu> list = new List<WFMenu>();
            ////根据用户账号加载可启动工作流
            //DataTable startdt = WorkFlowTemplate.GetAllowsStartWorkFlows(UserService.CurrUserInfo.Id);
            ////string tmpClassId = "###";
            ////装载流程分类
            //foreach (DataRow dr in startdt.Rows)
            //{
            //    if (dr["FatherId"] != null)
            //    {
            //        WFMenu childMenu = new WFMenu();
            //        //if (dr["FatherId"].ToString() == "1")
            //        //{
            //        //childMenu.FatherFrkId = "5";
            //        //}
            //        //else
            //        //{
            //        //   childMenu.FatherFrkId = dr["FatherId"].ToString();
            //        //}
            //        childMenu.Caption = dr["TaskCaption"].ToString();
            //        string nowtaskid = dr["WorktaskId"].ToString();
            //        string workflowId = dr["WorkFlowId"].ToString();

            //        //string url = dr["clmgrurl"].ToString();
            //        //if (url.Length > 0)
            //        //    childMenu.url = url;
            //        childMenu.url = "/WorkFlow/Start/Index?workflowid=" + workflowId + "&worktaskId=" + nowtaskid;
            //        childMenu.FrkId = nowtaskid;
            //        childMenu.img = "/Content/icon/WaitTask/Claiming.png";
            //        list.Add(childMenu);
            //    }
            //}
            //ViewBag.WFList = list;
        }

        /// <summary>
        /// 当前登录人可办理工作 WS 2011-10-20
        /// </summary>
        //private void WFCtrlMenu()
        //{
        //    List<WFMenu> list = new List<WFMenu>();
        //    string sql = "select * from WebFrkTree";
        //    SqlDataItem sqlItem = new SqlDataItem();
        //    sqlItem.CommandText = sql;
        //    ClientDBAgent agent = new ClientDBAgent();
        //    DataTable table = agent.ExecuteDataTable(sqlItem);
        //    foreach (DataRow row in table.Rows)
        //    {
        //        WFMenu detail = new WFMenu();
        //        detail.FrkId = row["FrkId"].ToString();//主键
        //        //计算数量
        //        if (detail.FrkId == "2")//未认领任务
        //        {
        //            //detail.Caption = row["Caption"] + "(" + WorkFlowInstance.GetClaimingTaskCount(_organizeService.GetStaffIdByUserName()).ToString() + ")";
        //            detail.Caption = "新到工作(" + WorkFlowInstance.GetClaimingTaskCount(UserService.CurrUserInfo.Id).ToString() + ")";
        //            detail.url = "/WorkFlow/Claiming";
        //            detail.img = "/Content/icon/WaitTask/Claiming.png";
        //            list.Add(detail);
        //        }
        //        if (detail.FrkId == "3")//已认领任务
        //        {
        //            detail.Caption = "未完工作(" + WorkFlowInstance.GetClaimedTaskCount(UserService.CurrUserInfo.Id).ToString() + ")";
        //            detail.url = "/WorkFlow/ClaimedTask";
        //            detail.img = "/Content/icon/WaitTask/ClaimedTask.png";
        //            list.Add(detail);
        //        }
        //        //暂时去除以下任务，以后再想办法合理查看已做任务 WS 2011.11.17 
        //        if (detail.FrkId == "4")//已完成任务
        //        {
        //            detail.Caption = row["Caption"] + "(" + WorkFlowInstance.GetCompletedTaskCount(_organizeService.GetStaffIdByUserName()).ToString() + ")";
        //            detail.url = "/WorkFlow/CompletedTask";
        //            detail.img = "/Content/icon/WaitTask/CompletedTask.png";
        //            list.Add(detail);
        //        }
        //        if (detail.FrkId == "6")//我参与的任务
        //        {
        //            detail.Caption = row["Caption"] + "(" + WorkFlowInstance.GetAllTaskCount(UserService.CurrUserInfo.Id).ToString() + ")";
        //            detail.url = "/WorkFlow/AllWorkTask";
        //            detail.img = "/Content/icon/WaitTask/AllWorkTask.png";
        //            list.Add(detail);
        //        }
        //        if (detail.FrkId == "7")//异常终止的任务
        //        {
        //            detail.Caption = row["Caption"] + "(" + WorkFlowInstance.GetAbnormalTaskCount(UserService.CurrUserInfo.Id).ToString() + ")";
        //            detail.url = "/WorkFlow/AbnormalTask";
        //            detail.img = "/Content/icon/WaitTask/AbnormalTask.png";
        //            list.Add(detail);
        //        }
        //    }
        //    ViewBag.WFCtrlList = list;
        //}


        #region 首页更多 CreatUser：ThinkWang CreatTime：2012-9-21
        /// <summary>
        /// 新到工作\待办工作
        ///  CreatUser:ThinkWang
        ///  CreatTime:2012-9-20 
        /// </summary>
        /// <param name="workType"></param>
        /// <param name="workStatus">1新到工作，2待办工作,3已完成未批复，4已批复</param>
        /// <returns></returns>
        public ActionResult ClaimMore(string workType = "", int workStatus = 1)
        {
            ViewBag.WorkType = workType;
            ViewBag.WorkStatus = workStatus;
            return View();
        }
        [HttpPost]
        public ActionResult ClaimMore(QueryBase query, string workType = "", int workStatus = 1)
        {
            ActionResult ar = null;
            switch (workStatus)
            {
                case 1://新到工作
                    ar = GetClaimingTasks(query, 100, workType);
                    break;
                case 2://待办工作
                    ar = GetClaimedTasks(query, 100, workType);
                    break;
                case 3://已完成未批复
                    ar = GetUnAuditTasks(query, 100, workType);
                    break;
                case 4://已批复
                    ar = GetAuditTasks(query, 100, workType);
                    break;
                //default:
                //    ar = Json(WebUtility.TojqGridData<TaskDetail>(new List<TaskDetail>(), query));
                //    break;
            }
            return ar;
        }
        /// <summary>
        ///已办未批复工作列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private ActionResult GetUnAuditTasks(QueryBase query, int topsize = 5, string workType = "")
        {
            //DataTable dt = WorkFlowInstance.WorkflowCompletedTask(UserService.CurrUserInfo.Id, topsize);
            //List<TaskDetail> list = new List<TaskDetail>();
            //ObjectMapper mapper = new ObjectMapper(typeof(DataRow), typeof(TaskDetail));
            //if (dt != null)
            //{
            //    foreach (DataRow dr in dt.Select(@"status=3 and flstatus=2 and IsSubmit=True and flowinscaption like'" + workType + "%'", "OperDateTime DESC"))
            //        list.Add(mapper.ConvertObject(dr) as TaskDetail);
            //}

            //var jqGridData = WebUtility.TojqGridData<TaskDetail>(list, query);
            return null;
        }
        /// <summary>
        ///已批复工作列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private ActionResult GetAuditTasks(QueryBase query, int topsize = 5, string workType = "")
        {
            //DataTable dt = WorkFlowInstance.WorkflowCompletedTask(UserService.CurrUserInfo.Id, topsize);
            //List<TaskDetail> list = new List<TaskDetail>();
            //ObjectMapper mapper = new ObjectMapper(typeof(DataRow), typeof(TaskDetail));
            //if (dt != null)
            //    foreach (DataRow dr in dt.Select("flstatus=3 and flowinscaption like'" + workType + "%'", "OperDateTime DESC"))
            //        list.Add(mapper.ConvertObject(dr) as TaskDetail);

            //var jqGridData = WebUtility.TojqGridData<TaskDetail>(list, query);
            return null;
        }
        #endregion

        /// <summary>
        ///  保存快捷操作菜单
        /// </summary>
        /// <param name="moduleIds"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveFastBar(string moduleIds)
        {
            string msg = "保存失败";
            string code = "300";
            if (new UserService().BatchAddUserModule(moduleIds))
            {
                msg = "保存成功";
                code = "200";
            }
            return Json(new CallbackStatus
            {
                message = msg,
                statusCode = code
            });

        }

        /// <summary>
        /// 获取当前登录人的变更提醒
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string GetBGTip()
        {
            //List<WF_CHANGEAPPLY> listApply = _changeApplyBLL.GetToDoChangeApplyList() ?? new List<WF_CHANGEAPPLY>();//代办变更申请
            //List<WF_CHANGEINFORM> listInfo = _changeInformBLL.GetToDoChangeInformList() ?? new List<WF_CHANGEINFORM>();//代办变更通知
            //List<WF_CHANGEORDER> listOrder = _changeOrderBLL.GeToDoChangeOrderList() ?? new List<WF_CHANGEORDER>();//代办变更令
            //int changeInfoByYZ = 0;
            //int changeInfoByJL = 0;
            //var entiy = _organizeService.GetOrganizeEntityById((UserService.CurrUserInfo.CompanyId ?? 0).ToString());
            //if (entiy.Code == "YZ")
            //{
            //    changeInfoByYZ = listInfo.Count;
            //    changeInfoByJL = 0;
            //}
            //else if (entiy.Code == "JL")
            //{
            //    changeInfoByJL = listInfo.Count;
            //    changeInfoByYZ = 0;
            //}
            return "";//string.Format("{{\"ChangeApply\":\"{0}\",\"ChangeInfoByYZ\":\"{1}\",\"ChangeInfoByJL\":\"{2}\",\"ChangeOrder\":\"{3}\"}}", listApply.Count, changeInfoByYZ, changeInfoByJL, listOrder.Count);
        }

        #region 3级菜单 ThinkWang 2013-10-21
        /// <summary>
        /// 顶部1级导航
        /// </summary>
        /// <returns></returns>
        public ActionResult HeaderNav()
        {
            //获取权限系统中当前登录人所能访问的所有菜单
            List<BaseModuleEntity> list = new ModuleService().GetCurrentModules() as List<BaseModuleEntity>;
            if (list != null)
            {
                //if (UserService.CurrUserInfo.IsAdministrator)
                //{//如果当前登录人是管理员，则进行模块过滤，只显示权限管理、日志管理 WS 2011.11.8
                //    string tags = "PERMISSION|LOG";
                //    list = new List<BaseModuleEntity>();
                //}
                //else
                //{
                var root = list.Find(x => x.Code == "DotNet");
                if (root != null)
                {
                    list = list.FindAll(x => x.ParentId == root.Id);//找到1级菜单项
                }
                //}
            }

            return View(list);
        }
        /// <summary>
        /// 左侧2、3级导航
        /// </summary>
        /// <param name="id">1级菜单ID</param>
        /// <returns></returns>
        public ActionResult LeftNav(int id = 0)
        {
            string MoudleIDs = "";
            if (id == 0)
            {
                List<BaseModuleEntity> Modulelist = new ModuleService().GetCurrentModules() as List<BaseModuleEntity>;
                if (Modulelist != null)
                {
                    var root = Modulelist.Find(x => x.Code == "DotNet");
                    if (root != null)
                    {
                        Modulelist = Modulelist.FindAll(x => x.ParentId == root.Id);//找到1级菜单项
                    }
                }
                if (Modulelist != null && Modulelist.Count > 0)
                {
                    if (UserService.CurrUserInfo.IsAdministrator)
                    {
                        id = Modulelist.Find(x => x.Code == "PERMISSION").Id ?? 0;
                    }
                    else
                        id = 10005577; //Modulelist.Find(x => x.Code == "Project.Information").Id ?? 0;
                }
            }
            //获取权限系统中当前登录人所能访问的所有菜单
            List<BaseModuleEntity> list = new ModuleService().GetCurrentModules() as List<BaseModuleEntity>;
            if (list != null)
            {
                list = GetAllChildeNode(list, id);//子项
            }
            for (int i = 0; i < list.Count; i++)
            {
                MoudleIDs += Convert.ToString(list[i].Id) + ",";
            }

            ViewBag.MoudleIDs = MoudleIDs.TrimEnd(new char[] { ',' }); ;
            ViewBag.ParentId = id;
            return View(list);
        }
        /// <summary>
        /// 获取当前用户所有功能模块说明图列表
        /// </summary>
        /// <param name="IDs">模块ID字符串,逗号分隔</param>
        /// <returns></returns>
        public ActionResult InstructionsData(string IDs)
        {
            List<PROJECT_INSTRUCTIONS> Alllist = new List<PROJECT_INSTRUCTIONS>();
            if (IDs != "")
            {
                string[] Strs = IDs.Split(',');
                for (int i = 0; i < Strs.Length; i++)
                {
                    //List<PROJECT_INSTRUCTIONS> list = _Instructions.GetAllListByModudleID(Convert.ToInt32(Strs[i])) ?? new List<PROJECT_INSTRUCTIONS>();
                    //Alllist.AddRange(list);
                }
            }
            return Json(Alllist);
        }
        /// <summary>
        /// 获取当前用户所有功能模块的浏览记录
        /// </summary>
        /// <param name="IDs">模块ID字符串,逗号分隔</param>
        /// <returns></returns>
        public ActionResult BrowserHistoryData(string IDs)
        {
            List<PROJECT_BROWSERHISTORY> HisList = new List<PROJECT_BROWSERHISTORY>();
            if (IDs != "")
            {
                string[] Strs = IDs.Split(',');
                for (int j = 0; j < Strs.Length; j++)//获取浏览记录
                {
                    //PROJECT_BROWSERHISTORY model = _BrowserHistoryBLL.GetAllBrowserHistoryByModudleIDAndUserID(Convert.ToInt32(Strs[j]), UserService.CurrUserInfo.Id) ?? new PROJECT_BROWSERHISTORY();
                    //HisList.Add(model);
                }
            }
            return Json(HisList);
        }
        /// <summary>
        /// 写入记录表
        /// </summary>
        /// <param name="MoudleID">功能模块ID</param>
        /// <returns></returns>
        public ActionResult WriteHistory(int MoudleID)
        {
            int RecordID = 0;
            PROJECT_BROWSERHISTORY model = new PROJECT_BROWSERHISTORY();
            model.BrowserHistory_UserID = UserService.CurrUserInfo.Id;
            model.BrowserHistory_MoudleID = MoudleID;
            //if (_BrowserHistoryBLL.AddBrowserHistory(model) > 0)
            //{
            //    RecordID = 1;
            //}
            return Json(RecordID);
        }
        /// <summary>
        ///   递归获取所有子菜单
        /// </summary>
        /// <param name="list"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<BaseModuleEntity> GetAllChildeNode(List<BaseModuleEntity> list, int parentId)
        {
            List<BaseModuleEntity> reList = new List<BaseModuleEntity>();
            List<BaseModuleEntity> tempList = list.FindAll(x => x.ParentId == parentId);
            reList.AddRange(tempList);
            foreach (var item in tempList)
            {
                reList.AddRange(GetAllChildeNode(list, item.Id.Value));
            }
            return reList;
        }

        #endregion

        #region 首页，选择、切换菜单  2016-10-09
        /// <summary>
        /// 项目列表页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ProjectList()
        {
            List<PROJECT_PRJINFO> list = _prjInfoBLL.GetPrjinfoByUserID();
            ViewBag.ProList = list;
            return View();
        }
        ///// <summary>
        ///// 获取 项目列表
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //public ActionResult GetProjectList(QueryBase query, string ProjectName = "")
        //{
        //    List<PROJECT_PRJINFO> list = new List<PROJECT_PRJINFO>();//_prjInfoBLL.GetlistByUserCode(ProjectName);
        //    var jqGridData = WebUtility.TojqGridData<PROJECT_PRJINFO>(list, query);
        //    return Json(jqGridData);
        //}
        /// <summary>
        ///  设置 当前 项目
        ///  ThinkWang
        ///  2013-3-26 15:14:16
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SetCurrentProject(int proID = 0)
        {
            string msg = "选择项目失败，请重新登录后重试";
            string code = "300";

            if (proID > 0)
            {
                UserService.CurrUserInfo.Themes = proID.ToString();
                UserService.CurrUserInfo.StaffId = proID.ToString();
                SetProjectCookie(proID);
                Settings.Refresh();//清空配置文件缓存
                //SetWorkFlowId(proID);
                msg = "选择成功";
                code = "200";
            }

            return Json(new CallbackStatus
            {
                message = msg,
                statusCode = code
            });

        }

        #endregion

        #region 设置工作流参数
        ///// <summary>
        ///// 获取工作流id
        ///// add by sqj at 2013-6-6 10:02:32
        ///// </summary>
        ///// <param name="dt">当前项目下所有工作流</param>
        ///// <param name="wfEnum">工作流枚举值</param>
        ///// <returns>返回工作流id</returns>
        //private string GetWorkFlowIdByWorkFlowClassType(DataTable dt, WFEnum wfEnum)
        //{
        //    DataRow[] drs = dt.Select(string.Format("Description='{0}'", (int)wfEnum));//过滤出施工计量流程的workflowid
        //    return (drs.Length == 0) ? string.Empty : drs[0]["workflowId"].ToString();
        //}
        ///// <summary>
        ///// 对工作流id赋值
        ///// </summary>
        //private void SetWorkFlowId(int prjId)
        //{
        //    string workflowid = string.Empty;
        //    PROJECT_PRJINFO proModel = _prjInfoBLL.GetEntityById(prjId);
        //    DataTable workflowDT = null;
        //    if (proModel != null)
        //    {
        //        workflowDT = WorkFlowClass.GetWorkflowsByClassId(proModel.WorkFlowClassId);//获得当前项目所有的workflowclass
        //    }
        //    WorkFlowSetting.Instance.WorkMeasureWFId = GetWorkFlowIdByWorkFlowClassType(workflowDT, WFEnum.WorkMeasure);
        //    WorkFlowSetting.Instance.VisionMeasureWFId = GetWorkFlowIdByWorkFlowClassType(workflowDT, WFEnum.VisionMeasure);
        //    WorkFlowSetting.Instance.VerifyMeasureWFId = GetWorkFlowIdByWorkFlowClassType(workflowDT, WFEnum.VerifyMeasure);
        //    WorkFlowSetting.Instance.ChangeRequestWFId = GetWorkFlowIdByWorkFlowClassType(workflowDT, WFEnum.ChangeRequest);
        //    WorkFlowSetting.Instance.ContractAddWFId = GetWorkFlowIdByWorkFlowClassType(workflowDT, WFEnum.ContractAdd);
        //    WorkFlowSetting.Instance.FundPlanWFId = GetWorkFlowIdByWorkFlowClassType(workflowDT, WFEnum.FundPlan);
        //    WorkFlowSetting.Instance.SupervisingWFId = GetWorkFlowIdByWorkFlowClassType(workflowDT, WFEnum.SupervisingMeasure);
        //    WorkFlowSetting.Instance.SchedulePlanWFId = GetWorkFlowIdByWorkFlowClassType(workflowDT, WFEnum.SchedulePlan);
        //    WorkFlowSetting.Instance.ScheduleReportWFId = GetWorkFlowIdByWorkFlowClassType(workflowDT, WFEnum.ScheduleReport);
        //}
        #endregion
        public bool SetProjectCookie(int ProjectID)
        {
            bool flag = false;
            HttpCookie ProjectCookie = Request.Cookies["ProjectID"];
            if (ProjectCookie != null)
            {
                ProjectCookie.Value = ProjectID.ToString();
                Response.SetCookie(ProjectCookie);
                flag = true;
            }
            else
            {
                HttpCookie ProjectIDcookie = new HttpCookie("ProjectID");
                ProjectIDcookie.Value = ProjectID.ToString();
                Response.AppendCookie(ProjectIDcookie);
                flag = true;
            }
            return flag;
        }
        #region 测试UI布局  仅UI设计人员使用
        public ActionResult TestUI()
        {
            return View();
        }
        #endregion


        public ActionResult Test(string get, string Distric, string Type)
        {
            string distric = UserService.CurrUserInfo.DepartmentId.ToString();//Request.Form["Distric"];
            if (get!="9")
            {
                string type = Request.Form["Type"];
                string json = "[";
                var list = ServiceManager.Instance.OrganizeService.GetOrganizeByCode("SFZ");
                foreach (Base_Organize row in list)
                {
                    if (row.BelongTo.Contains(distric))
	                    {
                            string Name = "";
                            string Longitude = "";
                            string Latitude = "";
                            Name = row.FullName.ToString();
                            //经纬度
                            if (row.Fax != null)
                            {
                                string Fax = row.Fax.ToString();
                                string[] fa = Fax.Split(',');
                                if (fa.Length > 1)
                                {
                                    Longitude = fa[1].ToString();
                                    Latitude = fa[0].ToString();
                                }
                            }
                            //根据收费站ID查询设备状态统计显示在地图上
                            DataTable dta = BllRoadwayUIRule.GetMeterStateTotalBySql(" PlacId = '" + row.Id + "'");
                            int allY = Convert.ToInt32(dta.Rows[0]["YTotal"]);
                            int allZ = Convert.ToInt32(dta.Rows[0]["ZTotal"]);
                            int all = Convert.ToInt32(dta.Rows[0]["Total"]);
                            json += "{\"Id\":\"" + row.Id + "\",\"Name\":\"" + Name + "\",\"Longitude\":\"" + Longitude + "\",\"Latitude\":\"" + Latitude + "\",\"AllY\":\"" + allY + "\",\"AllZ\":\"" + allZ + "\",\"All\":\"" + all + "\"},";
	                    } 
                  
                }
                json = json.TrimEnd(',') + "]";
                return Content(json);
            }
              //get=9  点击地图弹出车道信息
            else
            {
                string json = "[";
                var list = ServiceManager.Instance.OrganizeService.GetOrganizeByCode("SFZ");
                foreach (Base_Organize row in list)
                {
                    if (row.BelongTo.Contains(distric))
                    {
                        string Name = "";
                        string Longitude = "";
                        string Latitude = "";
                        Name = row.FullName.ToString();
                        //经纬度
                        if (row.Fax != null)
                        {
                            string Fax = row.Fax.ToString();
                            string[] fa = Fax.Split(',');
                            if (fa.Length > 1)
                            {
                                Longitude = fa[1].ToString();
                                Latitude = fa[0].ToString();
                            }
                        }
                        //根据收费站ID查询设备状态统计显示在地图上
                        DataTable dta = BllRoadwayUIRule.GetMeterStateTotalBySql(" PlacId = '" + row.Id + "'");
                        int allY = Convert.ToInt32(dta.Rows[0]["YTotal"]);
                        int allZ = Convert.ToInt32(dta.Rows[0]["ZTotal"]);
                        int all = Convert.ToInt32(dta.Rows[0]["Total"]);
                        json += "{\"Id\":\"" + row.Id + "\",\"Name\":\"" + Name + "\",\"Longitude\":\"" + Longitude + "\",\"Latitude\":\"" + Latitude + "\",\"AllY\":\"" + allY + "\",\"AllZ\":\"" + allZ + "\",\"All\":\"" + all + "\"},";
                    }
                }
                json = json.TrimEnd(',') + "]";
                return Content(json);
            }
           
        }

        public ActionResult GetMeterTotal(string get)
        {
            string json = "[";
            string distric = UserService.CurrUserInfo.DepartmentId.ToString();
            string sql = "";
            if (distric!="200000215")
            {
                sql = " and placid in ( select id FROM [KR_EPMPermission_RLX].[dbo].[Base_Organize] where parentid='" + distric + "') ";
            }
            DataTable dta = BllRoadwayUIRule.GetMeterStateTotalBySql(" 1=1 " + sql);
            int YTotal = Convert.ToInt32(dta.Rows[0]["YTotal"]);
            int ZTotal = Convert.ToInt32(dta.Rows[0]["ZTotal"]);
            int Total = Convert.ToInt32(dta.Rows[0]["Total"]);
            json += "{\"Total\":\"" + Total + "\",\"ZTotal\":\"" + ZTotal + "\",\"YTotal\":\"" + YTotal + "\"},";

            json = json.TrimEnd(',') + "]";


            return Content(json);
        }
        //public ActionResult GetTracking(int ID)
        //{

        //}
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult TrackingList(int ID)
        {
            //List<PROJECT_SEGMENT> newList = new List<PROJECT_SEGMENT>();

            //PROJECT_SEGMENT Visionmodel = new PROJECT_SEGMENT();
            //Visionmodel.SEGMENT_TYPE = 2;
            //Visionmodel.listItem = _segmentBLL.GetlistByPrjinfoID(2, 4) ?? new List<PROJECT_SEGMENT>();
            //for (int i = 0; i < Visionmodel.listItem.Count; i++)
            //{
            //    Visionmodel.SEGMENT_COUNTMAN += Visionmodel.listItem[i].SEGMENT_ID + ",";
            //}
            //Visionmodel.SEGMENT_COUNTMAN = Visionmodel.SEGMENT_COUNTMAN.TrimEnd(',');


            //PROJECT_SEGMENT Supermodel = new PROJECT_SEGMENT();
            //Supermodel.SEGMENT_TYPE = 5;
            //Supermodel.listItem = _segmentBLL.GetlistByPrjinfoID(5, 4) ?? new List<PROJECT_SEGMENT>();
            //for (int i = 0; i < Supermodel.listItem.Count; i++)
            //{
            //    Supermodel.SEGMENT_COUNTMAN += Supermodel.listItem[i].SEGMENT_ID + ",";
            //}
            //Supermodel.SEGMENT_COUNTMAN = Supermodel.SEGMENT_COUNTMAN.TrimEnd(',');


            //PROJECT_SEGMENT Verifymodel = new PROJECT_SEGMENT();
            //Verifymodel.listItem = _segmentBLL.GetlistByPrjinfoID(4, 4) ?? new List<PROJECT_SEGMENT>();
            //Verifymodel.SEGMENT_TYPE = 4;
            //for (int i = 0; i < Verifymodel.listItem.Count; i++)
            //{
            //    Verifymodel.SEGMENT_COUNTMAN += Verifymodel.listItem[i].SEGMENT_ID + ",";
            //}
            //Verifymodel.SEGMENT_COUNTMAN = Verifymodel.SEGMENT_COUNTMAN.TrimEnd(',');
            //newList.Add(Visionmodel); newList.Add(Supermodel); newList.Add(Verifymodel);
            //DataTable Parameterdt = _Instructions.GetJLJCParameter(newList) ?? new DataTable();
            //string WorkFlowIDs = "";
            //DataTable dt = null;
            //DataTable Alldt = new DataTable();
            //switch (ID)
            //{
            //    case 1:
            //        WorkFlowIDs = WorkFlowSetting.Instance.WorkMeasureWFId;
            //        break;
            //    case 2:
            //        WorkFlowIDs = WorkFlowSetting.Instance.VisionMeasureWFId;
            //        break;
            //    case 3:
            //        WorkFlowIDs = WorkFlowSetting.Instance.VerifyMeasureWFId;
            //        break;
            //    case 4:
            //        WorkFlowIDs = WorkFlowSetting.Instance.SupervisingWFId;
            //        break;
            //    case 5:
            //        WorkFlowIDs = Settings.Instance.FundPlanWFId + "," + Settings.Instance.VisionFundPlanWFId + "," + Settings.Instance.VerifyFundPlanWFId + "," + Settings.Instance.SupervisingPlanWFId
            //            + Settings.Instance.CwbzToWzbzWfID + "," + Settings.Instance.CwbzToZjbzWfID + "," + Settings.Instance.CwbzToXtbzWfID + "," + Settings.Instance.CwbzToAjbzWfID
            //            + Settings.Instance.CwbzToGcbzToHtbzWfID + "," + Settings.Instance.CwbzWfID;
            //        break;
            //    case 6:
            //        WorkFlowIDs = Settings.Instance.ImprestWFId + "," + Settings.Instance.VisionImprestWFId + "," + Settings.Instance.VerifyImprestWFId + "," + Settings.Instance.SupervisingImprestWFId;
            //        break;
            //}
            //string[] WorkFlowID = null;// WorkFlowIDs.Split(',');
            ////for (int i = 0; i < WorkFlowID.Length; i++)
            ////{
            ////dt = _Instructions.GetProcessTracking(WorkFlowID);
            //Alldt.Merge(dt);
            ////}
            //ViewBag.TrackList = Alldt;
            return View();
        }
    }
}
